package com.bishe.serivce.Impl;

import cn.hutool.core.util.StrUtil;
import com.bishe.dao.AdminDao;
import com.bishe.pojo.Admin;
import com.bishe.pojo.LoginModel;
import com.bishe.pojo.User;
import com.bishe.serivce.IAdminService;
import com.bishe.utils.EcoBootException;
import com.bishe.utils.JobUtil;
import com.bishe.utils.JwtUtil;
import com.bishe.utils.SqlQueryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * admin接口实现
 * @date 2022/03/20 41:08:16
 */
@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private AdminDao adminDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public List<Admin> findAll() {
        return adminDao.findAll();
    }

    @Override
    public Admin findById(String id) {
        return adminDao.findById(id);
    }

    @Override
    public void deleteById(String id) {
        adminDao.deleteById(id);
    }

    @Override
    public void updateById(Admin admin) {
        adminDao.updateById(admin);
    }

    @Override
    public void save(Admin admin) {
        adminDao.save(admin);
    }

    @Override
    public LoginModel login(LoginModel loginModel) {
        Admin one = new SqlQueryUtils<Admin>(Admin.class, jdbcTemplate).eq(Admin::getUserName, loginModel.getUserName()).eq(Admin::getPassWord, loginModel.getPassWord()).getOne();
        if (one == null){
            throw new EcoBootException("用户名密码错误！");
        }
        String id = one.getId();
        String token = JobUtil.login("admin", id); //登录 获取token

        LoginModel loginModel1 = new LoginModel();
        loginModel1.setType("admin");
        loginModel1.setUserName(one.getUserName());
        loginModel1.setToken(token);
        return loginModel1; //返回登录后的数据
    }

    @Override
    public void addOrUpdate(Admin admin, HttpServletRequest httpServletRequest) {
        //保存
        if (StrUtil.isEmpty(admin.getId())|| findById(admin.getId()) == null){
            admin.setId(StrUtil.uuid());
            save(admin);
            return;
        }
        //修改
        updateById(admin);
    }
}